import { cloneDeep } from 'lodash-es';
import { ConditionValue } from './types';
import { EditorType } from '../../../../dynamic-form';

export class InputGroupValue implements ConditionValue {

    editorType: EditorType = 'input-group';

    // 通过弹窗返回的若干个值对象构成的数组
    value: any[];

    // 控件内显示的值
    displayText: string;

    // 弹窗模式下，取列表中哪个字段的值映射到当前字段
    valueField: string;

    // 是否是手动输入的值
    isInputText: boolean;

    constructor(initialData: {
        value: any[];
        displayText: string;
        displayField: string;
        isInputText: boolean;
    } = { value: [], displayText: '', displayField: '', isInputText: false }
    ) {
        this.value = initialData.value;
        this.displayText = initialData.displayText;
        this.valueField = initialData.displayField;
        this.isInputText = initialData.isInputText;
    }

    clear(): void {
        this.value = [];
        this.displayText = '';
        this.valueField = '';
    }

    getPropValue(item: any, fieldPath: Array<string>): any {
        if (fieldPath.length > 1) {
            const pathToken = fieldPath.shift() as string;
            return item[pathToken] ? this.getPropValue(item[pathToken], fieldPath) : '';
        }
        return item[fieldPath[0]];
    }

    getTextValue(targetField: string): string {
        const fieldPath = targetField.split('.');
        const displayValues = this.value.map((item: any) => this.getPropValue(item, cloneDeep(fieldPath)));
        return displayValues && displayValues.length ? displayValues.join(',') : '';
    }

    getValue(): string {
        const fieldPath = this.valueField.split('.') || [];
        const values = this.value.map(item => this.getPropValue(item, cloneDeep(fieldPath)));
        return values && values.length ? values.join(',') : '';
    }

    setValue(value: any) {
        throw new Error("Method not implemented.");
    }

    isEmpty(): boolean {
        return !this.displayText;
    }
}
